package com.flea.hclv.controller;

import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.service.*;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.ControllerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 财务计算控制器类
 */
@RequestMapping("/flea/hclv/calFinance")
@Controller
public class HFinanceController {
  @Autowired
  private HTravelGroupService travelGroupService;
  @Autowired
  private HSubmitAccountService hSubmitAccountService;
  @Autowired
  private HProductService productService;
  @Autowired
  private HServiceOrderService hServiceOrderService;
  @Autowired
  private HServicePayRebackItemService hServicePayRebackItemService;
  @Autowired
  private HVisitorOrderService hVisitorOrderService;
  @Autowired
  private HVisitorRebackPaymentRecoderService hVisitorRebackPaymentRecoderService;
  @Autowired
  private HTimeTableService hTimeTableService;




  /**
   * 组团社
   * 根据团显示团列表中的信息，计算团的费用；
   * 外卖总价---总交易价（供应商）；
   * 减去导游报销的总金额；
   * 已经支付给供应商
   * 减去一个团的退款金额(游客退款金额)；
   *

   * 供应商退给自己的
   * @return
   */
  @RequestMapping("calFinanceGroupByGroup")
  @ResponseBody
  public ServerResponse<FleaPage<HTravelGroup>> calFinanceGroupByGroup(FleaPage<HTravelGroup> paging,
      HttpServletResponse response, HttpServletRequest request){


    // 1、团名称
    // 2、班期的时间
    //3、人数范围
    //4、负责人姓名
    //5、团的状态
		String model = request.getParameter("model");
    String orgDeptId = FleaOrgUtils.getCurrentUserDeptUuid(request);
    ServerResponse<FleaPage<HTravelGroup>> result = null;
    try {
      result = travelGroupService.findMyGroupForPage(request,model,paging.getCurPage(),paging.getPageSize());
      if(result.isSuccess()&&result.getData()!=null){
        FleaPage<HTravelGroup> travelGroups =  (FleaPage<HTravelGroup>)result.getData();
        List<HTravelGroup> datas = new ArrayList<>();
        for (HTravelGroup t:travelGroups.getCurPageData()) {
          //利润  总收入-总支出
          Float profit =0f;

          //报账信息
          JSONObject sbumitAccontInfo = this.getSubmitAccountMoneyInfos(orgDeptId,t.getId());
          Float bills = sbumitAccontInfo.getFloat("bills");
          if(bills==null){
            bills = 0f;
          }
          t.setBills(bills);
          Float guidCost = sbumitAccontInfo.getFloat("guidCost");
          t.setGuidCost(guidCost);
          if(guidCost==null){
            guidCost=0f;
          }
          boolean isMakeBill = sbumitAccontInfo.getBooleanValue("isMakeBill");
          t.setMakeBill(isMakeBill);
         // 游客订单金额
          JSONObject visitorOrderInfo = this.getGroupVisitorOrderMoneyInfos(t.getId());
          Float visitorShouldPay = visitorOrderInfo.getFloat("visitorShouldPay");
          t.setVisitorShouldPay(visitorShouldPay);
          Float visitorActualPay = visitorOrderInfo.getFloat("visitorActualPay");
          t.setVisitorActualPay(visitorActualPay);
          Float allTotalPayBack = visitorOrderInfo.getFloat("allTotalPayBack");
          t.setAllTotalPayBack(allTotalPayBack);
          Float totalGetMoney = visitorOrderInfo.getFloat("totalGetMoney");
          t.setTotalGetMoney(totalGetMoney);
          //组织结构金额
          JSONObject serviceOrderInfo = this.getGroupServiceOrderMoneyInfos(orgDeptId,t.getId());
          Float shoulPay = serviceOrderInfo.getFloat("shoulPay");
          t.setShoulPay(shoulPay);
          Float actulPay = serviceOrderInfo.getFloat("actulPay");
          t.setActulPay(actulPay);
          Float rebackPayTotal = serviceOrderInfo.getFloat("rebackPayTotal");

          t.setRebackPayTotal(rebackPayTotal);
          Float getRebackTotal = serviceOrderInfo.getFloat("getRebackTotal");
          t.setGetRebackTotal(getRebackTotal);
          Float totalPayMoney = serviceOrderInfo.getFloat("totalPayMoney");
          t.setTotalPayMoney(totalPayMoney);
          profit = (totalGetMoney == null ? 0f : totalGetMoney) - totalPayMoney - bills - guidCost;
          t.setProfit(profit);
          datas.add(t);
        }
        travelGroups.setCurPageData(datas);
        return ServerResponse.createBySuccess(travelGroups);
      }
     } catch (Exception e) {
      e.printStackTrace();
      return  ServerResponse.createByErrorMessage(e.getMessage());
    }


    return result;
  }

  //根据团获取所有游客订单总应支付金额;总实际支付金额，排除 取消和关闭的订单；根据这些订单获取
  private JSONObject getSubmitAccountMoneyInfos(String orgDeptId,String groupId){
    JSONObject  resultJson = new JSONObject();
    ServerResponse<HSubmitAccount> result = hSubmitAccountService.selectByTravelGroupIdAndPayDeptId(groupId,orgDeptId);
    if (!result.isSuccess()){
      return resultJson;
    }

    HSubmitAccount  account =result.getData();

    Float goCost =0f;
    Float guidCost =0f;
    Boolean isMakeBill = false;

    if(null!=account){
       goCost =  ((account.getGroupMoney()==null?0:account.getGroupMoney()) - (account.getTotal()==null?0:account.getTotal()));
      guidCost = account.getGuideCost();
      isMakeBill = true;
    }

    resultJson.put("guidCost",guidCost);
    resultJson.put("bills",goCost);
    resultJson.put("isMakeBill",isMakeBill);
    return resultJson;
  }

  /**
   * 游客订单费用
   * @param groupId
   * @return
   */
  private JSONObject getGroupVisitorOrderMoneyInfos(String groupId){
    JSONObject  resultJson = new JSONObject();
    List<HVisitorOrder> hVisitorOrders = hVisitorOrderService.findByGroupIdToList(groupId);
    Float visitorShouldPay = 0f;
    Float visitorActualPay = 0f;
    List<String> validOrder = new ArrayList<>();
    for (HVisitorOrder vorder: hVisitorOrders
    ) {
      String vorderStatus = vorder.getStatus();
      if(!HConstant.D_ORDER_STATUS_CLOSE.equals(vorderStatus)&&!HConstant.D_ORDER_STATUS_CANCEL.equals(vorderStatus)){
        visitorShouldPay+= vorder.getTotalAmount()==null?0:vorder.getTotalAmount();
        visitorActualPay+= vorder.getPayment()==null?0:vorder.getPayment();
      }
      validOrder.add(vorder.getOrderNo());
    }
    Float allTotalPayBack = 0f;
    //根据上面的过滤后的所有的订单id或者订单号，计算这些订单的所有的退款记录信息，退款总金额
    List<HVisitorRebackPaymentRecoder> visitorRebackReocders = hVisitorRebackPaymentRecoderService.findRebackbyOrderNos(validOrder);
    for (HVisitorRebackPaymentRecoder vRebackOrder:visitorRebackReocders
    ) {
      allTotalPayBack+= vRebackOrder.getRebackPayment()==null?0:vRebackOrder.getRebackPayment();
    }
    resultJson.put("visitorShouldPay",visitorShouldPay);
    resultJson.put("visitorActualPay",visitorActualPay);
    resultJson.put("allTotalPayBack",allTotalPayBack);
    resultJson.put("totalGetMoney",visitorActualPay-allTotalPayBack);
    return resultJson;
  }
  // 根据团，查询获取与团相关的服务订单; 应该付款多少；支付了多少；退款了多少；继续支付了多少；最终实际支付了多少
  private JSONObject getGroupServiceOrderMoneyInfos(String orgDeptId,String groupId){
    JSONObject  resultJson = new JSONObject();
    ServerResponse groupServiceOrderResult = null;
    Float shoulPay = 0f;
    Float actulPay = 0f;
    //退款给供应商多少钱
    Float rebackPayTotal =0f;
    Float getRebackTotal = 0f;
    try {
      groupServiceOrderResult = hServiceOrderService.findByGroupId(groupId);
      if(groupServiceOrderResult.isSuccess() && groupServiceOrderResult.getData()!=null){
        HServiceOrder groupServiceOrder = (HServiceOrder)groupServiceOrderResult.getData();
        shoulPay = groupServiceOrder.getShouldPayment();
        actulPay = groupServiceOrder.getActualPayment();
        String orderNo = groupServiceOrder.getOrderNo();

        List<HServicePayRebackItem> rebackPays = hServicePayRebackItemService.findByPayOrgIdAndOrderNo(orgDeptId,orderNo);
        for (HServicePayRebackItem pyItem:rebackPays
        ) {
          rebackPayTotal+= pyItem.getRebackMoney()==null?0:pyItem.getRebackMoney();
        }
        //供应商退钱给我多少
        List<HServicePayRebackItem> getBackPays = hServicePayRebackItemService.getBackPaysByBackOrgIdAndOrderNo(orgDeptId,orderNo);
        for (HServicePayRebackItem rebackItem: getBackPays
        ) {
          getRebackTotal+= rebackItem.getRebackMoney()==null?0:rebackItem.getRebackMoney();;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    resultJson.put("shoulPay",shoulPay);
    resultJson.put("actulPay",actulPay);
    resultJson.put("rebackPayTotal",rebackPayTotal);
    resultJson.put("getRebackTotal",getRebackTotal);
    resultJson.put("totalPayMoney",actulPay+getRebackTotal-rebackPayTotal);
    return resultJson;
  }

  /**
   * 供应商根据每个产品的班期计算费用；每个班期卖了个座位，导游报销费用，（车队）
   * @return
   */
  public ServerResponse calFinanceGroupByProductTimeTable(){
    return null;
  }
  /**
   * 产品卖出的总人数，总金额等，点击，可以看到每个班期卖出多少个座位，收到多少钱
   * @return
   */
  public void calFinanceGroupByProduct(HttpServletRequest request, FleaPage<HProduct> paging,
      HttpServletResponse response, String model){

    FleaPage<HProduct> pageList = productService.findForGird(paging.getCurPage(), paging.getPageSize(), model, request);
    ControllerResult conresult = new ControllerResult(pageList);
    conresult.set(true, "操作成功");
    conresult.WritePagingDataToPage(response, pageList);

  }
  @ResponseBody
  @RequestMapping("auidtByProduct")
  public ServerResponse auidtByProduct(FleaPage<HProduct> paging,HttpServletRequest request,HttpServletResponse response){

    String model = request.getParameter("model");
    //根据产品 统计产品卖了多少人  卖了多少钱  每个班期卖了多少钱  每个班期卖了多少人
    // 去查询与产品相关的订单
    FleaPage<HProduct> pageList = productService.findForGird(paging.getCurPage(), paging.getPageSize(), model, request);
    if(null!=pageList && pageList.getCurPageData()!=null && pageList.getCurPageData().size()>0){
     List<HProduct> products =  pageList.getCurPageData();
      List<HProduct> newLists = new ArrayList<>();
      for (HProduct p:products) {
        String productId = p.getId();
        Integer productTotalPerson =0;
        Float productTotal = 0f;
        List<HTimeTable> timeTables = hTimeTableService.getByProductId(productId);
        for (HTimeTable timeTable: timeTables) {
          try {
            List<HServiceOrder> serviceOrders =  hServiceOrderService.findByTimeTableIdToList(timeTable.getId());
            for (HServiceOrder hs:serviceOrders) {
              List<HVisitorOrder> visitorOrders = hVisitorOrderService.findByProductTimeTableIdToList(hs.getTimeTableId());
              for (HVisitorOrder ho: visitorOrders
              ) {
                //每个订单人数
                productTotalPerson+= ho.getQuantity()==null?0:ho.getQuantity();
              }
            }
            p.setProductTotalPerson(productTotalPerson);
          } catch (Exception e) {
            e.printStackTrace();
            return  ServerResponse.createByErrorMessage(e.getMessage());
          }
        }
        newLists.add(p);
      }
      pageList.setCurPageData(newLists);
    }
    return  ServerResponse.createBySuccess(pageList);
  }
  @ResponseBody
  @RequestMapping("auidtByProductId")
  public ServerResponse auidtByProductId(FleaPage<HProduct> paging,HttpServletRequest request,HttpServletResponse response){

    String productId = request.getParameter("model");
    if(StringUtil.isEmpty(productId)){
      return ServerResponse.createByErrorMessage("产品参数Id为空");
    }
    ServerResponse<FleaPage<HTimeTable>> result = null;
    try {
      result = hTimeTableService.getByProductIdPaging(productId, paging.getCurPage(), paging.getPageSize());
      if (result.isSuccess() && result.getModel() != null) {
        //todo 类型错误
        FleaPage<HTimeTable> tableFleaPage = result.getData();
        if (null != tableFleaPage && tableFleaPage.getCurPageData() != null) {
          List<HTimeTable> timeTables = tableFleaPage.getCurPageData();
          List<HTimeTable> newTimeTables = new ArrayList<>();
          for (HTimeTable timeTable : timeTables) {
            Integer totalPerson = 0;
            List<HVisitorOrder> vorders =   hVisitorOrderService.findByProductTimeTableIdToList(timeTable.getId());
            for (HVisitorOrder v: vorders) {
              totalPerson += v.getQuantity()==null?0:v.getQuantity();
            }
            List<HTravelGroup> travelGroups = travelGroupService.findByTimeTableId(timeTable.getId());
            Float groupShouldPay = 0f;
            Float groupActulPay =0f;
            Float groupRebackPayTotal =0f;
            Float groupTotalPayMoney =0f;
            for (HTravelGroup t:travelGroups
            ) {
              //购买方id
             String orgDeptId = t.getServiceOrgId();
              JSONObject serviceOrderInfo = this.getGroupServiceOrderMoneyInfos(orgDeptId,t.getId());

              Float shoulPay = serviceOrderInfo.getFloat("shoulPay");
              t.setShoulPay(shoulPay);

              Float actulPay = serviceOrderInfo.getFloat("actulPay");
              t.setActulPay(actulPay);
              Float rebackPayTotal = serviceOrderInfo.getFloat("rebackPayTotal");

              t.setRebackPayTotal(rebackPayTotal);
              Float getRebackTotal = serviceOrderInfo.getFloat("getRebackTotal");
              t.setGetRebackTotal(getRebackTotal);
              Float totalPayMoney = serviceOrderInfo.getFloat("totalPayMoney");
              t.setTotalPayMoney(totalPayMoney);
              if(shoulPay==null){
                shoulPay=0f;
              }
              if(rebackPayTotal==null){
                rebackPayTotal=0f;
              }
              if(getRebackTotal==null){
                getRebackTotal=0f;
              }
              if(totalPayMoney==null){
                totalPayMoney=0f;
              }
              groupShouldPay+=shoulPay;
              groupActulPay+=rebackPayTotal;
              groupRebackPayTotal +=getRebackTotal;
              groupTotalPayMoney +=totalPayMoney;
            }
            timeTable.setGroupActulPay(groupActulPay);
            timeTable.setGroupShouldPay(groupShouldPay);
            timeTable.setGroupRebackPayTotal(groupRebackPayTotal);
            timeTable.setGroupTotalPayMoney(groupTotalPayMoney);
            timeTable.setTotalSaledPerson(totalPerson);
            newTimeTables.add(timeTable);
          }

          tableFleaPage.setCurPageData(newTimeTables);
          return ServerResponse.createBySuccess(tableFleaPage);
        }
      }
    }
    catch (Exception e){
    e.printStackTrace();
    return  ServerResponse.createByErrorMessage(e.getMessage());
    }
    return result;
  }
}